/*
 * serializeUtils.cpp
 *
 *  Created on: 11/12/2012
 *      Author: Julian Ovalle
 */

#include <iostream>
#include <serializationUtils.h>

float deSerializeFloat(uint8_t *buf) {

    union {
        float f;
        uint8_t c[4];
    } floating;

    for (int k = 0; k < 4; k++) {
        floating.c[3 - k] = *(buf + k);
    }

    return floating.f;

}

void serializeFloat(uint8_t *buf, float value) {

    if (buf == NULL) {
        return;
    }

    union {
        float f;
        uint8_t c[4];
    } floating;

    floating.f = value;

    for (int k = 0; k < 4; k++) {
        *(buf + k) = floating.c[3 - k];
    }

}

int deSerializeInt(uint8_t *buf) {

    union {
        uint8_t c[4];
        int val;
    } integer;

    for (int k = 0; k < 4; k++) {
        integer.c[3 - k] = *(buf + k);
    }

    return integer.val;

}

void serializeInt(uint8_t *buf, int value) {

    if (buf == NULL) {
        return;
    }

    union {
        uint8_t c[4];
        int val;
    } integer;

    integer.val = value;

    for (int k = 0; k < 4; k++) {
        *(buf + k) = integer.c[3 - k];
    }

}

short int deSerializeShort(uint8_t *buf) {

    union {
        uint8_t c[2];
        short int val;
    } short_int;

    if (buf == NULL) {
        return -1;
    }

    short_int.c[1] = *buf;
    short_int.c[0] = *(buf + 1);

    return short_int.val;
}

void serializeShort(uint8_t *buf, short int value) {

    if (buf == NULL) {
        return;
    }
    union {
        uint8_t c[2];
        short int val;
    } short_int;

    short_int.val = value;

    *buf = short_int.c[1];
    *(buf + 1) = short_int.c[0];

    return;
}

double deSerializeDouble(uint8_t *buf) {
    union {
        uint8_t c[8];
        double d;
    } doubling;

    for (int k = 0; k < 8; k++) {
        doubling.c[7 - k] = *(buf + k);
    }

    return doubling.d;

}

void serializeDouble(uint8_t *buf, double value) {
    if (buf == NULL) {
        return;
    }

    union {
        uint8_t c[8];
        double d;
    } doubling;

    doubling.d = value;

    for (int k = 0; k < 8; k++) {
        *(buf + k) = doubling.c[7 - k];
    }

}
